import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/utils/log.dart';

class TextFieldWidget extends StatefulWidget {
  const TextFieldWidget({
    Key? key,
    required this.name,
    required this.label,
    this.required = false,
    this.readOnly = false,
    this.disabled = false,
    this.initialValue,
  }) : super(key: key);

  final String name;
  final String label;
  final bool required;
  final bool readOnly;
  final bool disabled;
  final String? initialValue;

  @override
  _TextFieldState createState() => _TextFieldState(
      name: name,
      label: label,
      required: required,
      readOnly: readOnly,
      disabled: disabled,
      initialValue: initialValue);
}

class _TextFieldState extends State<TextFieldWidget> {
  String name;
  String label;
  bool required;
  bool readOnly;
  bool disabled;
  String? initialValue;
  _TextFieldState({
    required this.name,
    required this.label,
    this.required = false,
    this.readOnly = false,
    this.disabled = false,
    this.initialValue,
  });
  final _fieldKey = GlobalKey<FormBuilderFieldState>();

  String? errorText;

  String? Function(String?) validator(context) {
    List<String? Function(String?)> validationList = [];
    switch (name) {
      case "email":
        validationList.add(FormBuilderValidators.email());
        break;
      default:
        break;
    }
    if (required) {
      validationList.add(
          FormBuilderValidators.required(errorText: "$label is required."));
    }
    return FormBuilderValidators.compose(validationList);
  }

  void updateError() async {
    setState(() => errorText = null);
    switch (name) {
      case "email":
        await Future.delayed(Duration(seconds: 3), () {
          Log.debug("yoshi");
        });
        setState(() => errorText = 'Email already taken.');
        return;
      default:
        return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return FormBuilderTextField(
      key: _fieldKey,
      name: name,
      enabled: !disabled,
      readOnly: readOnly,
      initialValue: initialValue,
      style: Theme.of(context).textTheme.titleSmall,
      decoration: InputDecoration(
        labelText: label,
        labelStyle: TextStyle(
          color: Get.isDarkMode ? Colors.white : Colors.black,
        ),
        errorText: errorText,
      ),
      validator: validator(context),
    );
  }
}
